/*
Java board game library.
Copyright (C) 2011  Deepesh Garg

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package d.g.boardgames.chess;

import java.util.List;

import d.g.boardgames.Board;
import d.g.boardgames.BoardEventListener;
import d.g.boardgames.BoardGUI;
import d.g.boardgames.Cell;


public class ChessMoveListener implements BoardEventListener {

	ChessBoardRenderProperties renderProperties;
	BoardGUI boardGui;
	
	List <Cell> validMoves;
	Cell fromCell;
	@Override
	public void boardAction(Board board, int row, int col) {
		ChessBoard chessBoard = (ChessBoard) board;
		Cell cell = new Cell(row, col);
		if (fromCell == null || validMoves == null || validMoves.size() == 0) {
			selectCell (chessBoard, cell);
		} else if (validMoves != null && validMoves.size() > 0) {
			if (validMoves.contains(new Cell(row, col))) {
				attemptMove(chessBoard, cell);
			} else {
				selectCell (chessBoard, cell);
			}
		}
	}
	
	private void selectCell (ChessBoard chessBoard, Cell cell) {
		fromCell = cell;
		validMoves = ChessMoveHelper.getValidMoves(chessBoard, fromCell) ;
		if (renderProperties != null) {
			renderProperties.setValidMoves(validMoves);
			renderProperties.setSelectedCell(fromCell);
		}
	}
	
	private void attemptMove (ChessBoard chessBoard, Cell cell) {
		Cell toCell = cell;
		//ChessMove chessMove = new ChessMove (fromCell, toCell);
		ChessMove chessMove = ChessMoveHelper.getChessMove(chessBoard, fromCell, toCell);
		ChessBoard newBoard = chessBoard.move(chessMove);
		boardGui.setBoard(newBoard);
		validMoves = null;
		renderProperties.setValidMoves(null);
		renderProperties.setSelectedCell(null);
		fromCell = null;
	}

	public ChessBoardRenderProperties getRenderProperties() {
		return renderProperties;
	}

	public void setRenderProperties(ChessBoardRenderProperties renderProperties) {
		this.renderProperties = renderProperties;
	}

	public BoardGUI getBoardGui() {
		return boardGui;
	}

	public void setBoardGui(BoardGUI boardGui) {
		this.boardGui = boardGui;
	}
}
